﻿using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LiteUart
{
    public partial class Form1 : Form
    {
        SerialPort serialPort1 = null;
        ShellStream st;
        int start = 0;

        [DllImport("user32", EntryPoint = "HideCaret")]
        private static extern bool HideCaret(IntPtr hWnd);
        public Form1()
        {
            this.serialPort1 = CreateSerialPort();
            InitializeComponent();
            console.GotFocus += console_Enter;
            
        }

        private SerialPort CreateSerialPort()
        {
            SerialPort serialPort = new System.IO.Ports.SerialPort();
            serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.SerialPort1_DataReceived);
            serialPort.ReadBufferSize = 1024;
            return serialPort;
        }
        //[DllImport("user32")]
        int lastCode = 0;
        public void Parse(char[] buffer, int len)
        {
            char[] stringBuffer = new char[len];
            int offset = 0;
            for (int i = 0; i < len; i++)
            {
                char c = buffer[i];
                Console.Write(" " + c + " (" + (int)c + ")");
                switch (c)
                {

                    case '\n':
                        stringBuffer[offset++] = '\n';
                        lastCode = start + offset;
                        break;
                    case '\r':
                        if (i+1<len && buffer[i + 1] == '\n')
                        {
                            continue;
                        }
                        else {
                            string text2 = new string(stringBuffer, 0, offset);
                            this.Invoke((EventHandler)(delegate
                            {
                                UpdateConsoleUi(text2, start, offset);
                            }));
                            start = lastCode;
                            offset = 0;
                            //Console.WriteLine("行首" + lastCode + " 索引" +start);
                        }
                       
                        //offset = 0;
                        //stringBuffer[offset++] = '\r';
                        break;
                    case '\a':
                        System.Media.SystemSounds.Beep.Play();
                        break;
                    case '\b':

                        if (offset != 0)
                        {
                            string text = new string(stringBuffer, 0, offset);
                            this.Invoke((EventHandler)(delegate
                            {
                                UpdateConsoleUi(text, start, offset);
                            }));
                            start += offset;

                           
                        }

                        start -= 1;
                        offset = 0;
                        
                        break;
                    default:
                        //if (c == '\n' && offset > 0 && stringBuffer[offset-1] != '\r') {
                        stringBuffer[offset++] = c;
                        // Console.Write(" "+c+" ("+(int)c+")");
                        break;
                }

            }
            if (offset != 0)
            {
                string text = new string(stringBuffer, 0, offset);
                this.Invoke((EventHandler)(delegate
                {
                    UpdateConsoleUi(text, start, offset);
                }));
                start += offset;
            }
            
        }

        private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                //因为要访问UI资源，所以需要使用invoke方式同步ui           
                char[] buffer = new char[1024];
                int len = serialPort1.Read(buffer, 0, 1024);
                Parse(buffer, len);

            }
            catch (Exception ex)
            {
                //响铃并显示异常给用户
                System.Media.SystemSounds.Beep.Play();
                MessageBox.Show(ex.Message);
            }
        }

        private void UpdateConsoleUi(string text, int startPosition, int len)
        {
            //if (start + len > console.TextLength)
            //    len = console.TextLength - start;

            HideCaret(console.Handle);
            console.SelectionStart = startPosition;
            console.SelectionLength = len;
            console.SelectedText = text;
            HideCaret(console.Handle);
           

        }
        private void Console_KeyDown(object sender, KeyEventArgs e)
        {

            // if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
            HideCaret(((RichTextBox)sender).Handle);
            e.Handled = true;
            if (st != null) 
            {
                switch (e.KeyCode) {
                    case Keys.Left:
                        st.Write(new string(new char[1] { (char)2 }));
                     
                        break;
                    case Keys.Right:
                        st.Write(new string(new char[1] { (char)3 }));
                        break;
                }
            }
            
            // Console.WriteLine(e.KeyValue);

        }

        private void Console_KeyPress(object sender, KeyPressEventArgs e)
        {
            HideCaret(((RichTextBox)sender).Handle);
            e.Handled = true;
            try
            {
               // if (serialPort1 == null)
               st.Write(e.KeyChar.ToString());
               // st.Write(e.KeyChar,0,1);
                Console.WriteLine(String.Format("::{0:X000}", (int)e.KeyChar));
                // else
                //     serialPort1.Write(e.KeyChar.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }





        private void Console_KeyUp(object sender, KeyEventArgs e)
        {
            e.Handled = true;
            HideCaret(((RichTextBox)sender).Handle);
        }

        public void openUartPort(string portName, string baudRate, string dataBits, string parity, string stopBits)
        {
            try
            {
                //将可能产生异常的代码放置在try块中
                //根据当前串口属性来判断是否打开
                if (serialPort1.IsOpen)
                {
                    //串口已经处于打开状态
                    serialPort1.Close();    //关闭串口
                }
                else
                {

                    serialPort1.PortName = portName;
                    serialPort1.BaudRate = Convert.ToInt32(baudRate);
                    serialPort1.DataBits = Convert.ToInt16(dataBits);
                    if (parity.Equals("None"))
                        serialPort1.Parity = System.IO.Ports.Parity.None;
                    else if (parity.Equals("Odd"))
                        serialPort1.Parity = System.IO.Ports.Parity.Odd;
                    else if (parity.Equals("Even"))
                        serialPort1.Parity = System.IO.Ports.Parity.Even;
                    else if (parity.Equals("Mark"))
                        serialPort1.Parity = System.IO.Ports.Parity.Mark;
                    else if (parity.Equals("Space"))
                        serialPort1.Parity = System.IO.Ports.Parity.Space;

                    if (stopBits.Equals("1"))
                        serialPort1.StopBits = System.IO.Ports.StopBits.One;
                    else if (stopBits.Equals("1.5"))
                        serialPort1.StopBits = System.IO.Ports.StopBits.OnePointFive;
                    else if (stopBits.Equals("2"))
                        serialPort1.StopBits = System.IO.Ports.StopBits.Two;

                    serialPort1.Open();


                }
            }
            catch (Exception ex)
            {
                //捕获可能发生的异常并进行处理

                //捕获到异常，创建一个新的对象，之前的不可以再用
                serialPort1 = CreateSerialPort();
                System.Media.SystemSounds.Beep.Play();
                MessageBox.Show(ex.Message);
            }
        }

        private void OpenSelectPort_Click(object sender, EventArgs e)
        {
            SelectPort selectPort = new SelectPort();
            selectPort.StartPosition = FormStartPosition.CenterScreen;
            selectPort.Owner = this;
            selectPort.ShowDialog();
        }

        private void About_Click(object sender, EventArgs e)
        {
            AboutBox1 aboutBox1 = new AboutBox1();
            aboutBox1.StartPosition = FormStartPosition.CenterScreen;
            aboutBox1.Owner = this;
            aboutBox1.ShowDialog();
        }

        private void SettingMenuItem_Click(object sender, EventArgs e)
        {
            SettingForm settingForm = new SettingForm();
            settingForm.StartPosition = FormStartPosition.CenterScreen;
            settingForm.Owner = this;
            settingForm.ShowDialog();
        }
        private void ResetConsoleFontSize()
        {
            SizeF sizeF = TextRenderer.MeasureText("a", new Font(console.Font.Name, console.Font.Size, console.Font.Style,
console.Font.Unit));
            int fontWidth = (int)(console.Width / sizeF.Width);
            int fontHeight = (int)(console.Height / sizeF.Height);
            toolStripSize.Text = "" + fontWidth + "x" + fontHeight;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            HideCaret(console.Handle);

            Form2 settingForm = new Form2();
            settingForm.StartPosition = FormStartPosition.CenterScreen;
            settingForm.Owner = this;
            settingForm.ShowDialog();


            //console.Text = "abc\nc";
            // Console.WriteLine("字符串长度："+ console.Text.Length);
        }

        private void St_DataReceived(object sender, Renci.SshNet.Common.ShellDataEventArgs e)
        {
            char[] s = Encoding.ASCII.GetChars(e.Data);
            Parse(s,s.Length);
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            ResetConsoleFontSize();
        }

        private void Console_MouseDown(object sender, MouseEventArgs e)
        {
            HideCaret(((RichTextBox)sender).Handle);
        }

        private void Console_MouseMove(object sender, MouseEventArgs e)
        {
            HideCaret(((RichTextBox)sender).Handle);
        }

        private void console_SelectionChanged(object sender, EventArgs e)
        {
            HideCaret(((RichTextBox)sender).Handle);
        }

        private void CopyMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void ceshiToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string user = "root";
            string pass = "Liping520";
            string host = "xueshengji.dingd.cn";




            //创建SSH connection
            var client = new SshClient(host, user, pass);

            //启动连接
            client.Connect();
            st = client.CreateShellStream("xterm", 100, 200, 100 * 25, 100 * 25, 1024);

            st.DataReceived += St_DataReceived;
            // st.WriteLine("ls");

            //var output = client.RunCommand("ls");

            //if(output.ExitStatus == 0)
            //{ 
            //    console.AppendText(output.Result);
            // }
            // else
            // {
            //     console.AppendText("出错");

            //  }

            // client.Disconnect();



        }

        private void console_TextChanged_1(object sender, EventArgs e)
        {
            HideCaret(((RichTextBox)sender).Handle);
        }

        private void console_CursorChanged(object sender, EventArgs e)
        {
            HideCaret(((RichTextBox)sender).Handle);
        }

        private void console_PreviewKeyDown_1(object sender, PreviewKeyDownEventArgs e)
        {
            HideCaret(((RichTextBox)sender).Handle);

        }

        private void console_MouseEnter(object sender, EventArgs e)
        {
            HideCaret(((RichTextBox)sender).Handle);
        }

        private void console_MouseHover(object sender, EventArgs e)
        {
            HideCaret(((RichTextBox)sender).Handle);
        }

        private void console_MouseUp(object sender, MouseEventArgs e)
        {
            HideCaret(((RichTextBox)sender).Handle);
        }

        private void console_Enter(object sender, EventArgs e)
        {
            HideCaret(((RichTextBox)sender).Handle);
        }
    }
}
